<?php

namespace App\Libs;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;

class TokenLibrary
{

    const key = 'slsqncudWdOws!#';

    /**
     * 生成token
     */
    public static function createToken($data, $overdue_time=7200, $prefix = 'token_front_')
    {
        if($prefix=='token_backend_'){
            $type='1';
        }else{
            $type='2';
        }
       // $data['type']=$type;
        $time = time();
        $payload = [
            //"iss" => "",
            //"aud" => "",
            "iat" => $time,
            "nbf" => $time,
            "exp" => $time+$overdue_time,
            "data" => $data
        ];
        $token = JWT::encode($payload, self::key, 'HS256');
        cache()->set($prefix.$data['user_id'], $token, $overdue_time);
        return 'bearer '.$token;
    }
 
    /**
     * 验证token
     */
    public static function validateToken($token)
    {
        if(!$token){
            return false;
        }
        if (strpos($token,'bearer') !== false) {
            $token = trim(ltrim($token,'bearer'));
        }
       // dd($token);exit;
        try {
            //JWT::$leeway = 60;//当前时间减去60，把时间留点余地
            #解码 JWT 并验证签名
            $decoded = JWT::decode($token, new Key(self::key, 'HS256'));
            #检查是否过期
            if (isset($decoded->exp)) {
                $expirationTime = $decoded->exp; // 获取过期时间戳
                $currentTime = time(); // 当前时间的时间戳
                if ($currentTime > $expirationTime) {
                    #令牌已过期
                    return false;
                } else {
                    #令牌有效且未过期
                    return $decoded;
                }
            } else {
                #令牌没有过期时间
                return false;
            }
            
        }catch (\Exception $e){
            $msg='Token validation failed: '.$e->getMessage();
            return false;
        }

    }

   //获取token信息
    public  static function getTokenInfo($token)
    {
        if (strpos($token,'bearer') !== false) {
            $token = trim(ltrim($token,'bearer'));
        }
        try {
            #解码 JWT 并验证签名
            $decoded = JWT::decode($token, new Key(self::key, 'HS256'));
            return $decoded;
            
        }catch (\Exception $e){
            $msg='Token validation failed: '.$e->getMessage();
            return false;
        }

    }




}
